/**
 * Copyright (c) 2016 Lenovo Group
 * All Rights Reserved.
 * 
 * Project Name:event-recorder
 * Create Time: 2016年4月28日 下午2:55:33
 */
package com.lenovo.lmrp.server.eventrecorder.domain.ticket;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lenovo.lmrp.api.model.entity.EngineerTracePO;
import com.lenovo.lmrp.base.event.EventContent;
import com.lenovo.lmrp.base.event.EventTopic;
import com.lenovo.sdc.framework.mq.AMQClient;
import com.lenovo.sdc.framework.mq.IMQReceiver;
import com.lenovo.sdc.framework.util.JSONHelper;
import com.lenovo.sdc.framework.util.exception.ErrorCode;
import com.lenovo.sdc.framework.util.exception.TraceableException;

/**
 * @author zhangzheng
 *
 */
public class EngineerEventService implements IMQReceiver{
    
    private static final Logger logger = LoggerFactory.getLogger(EngineerEventService.class);
    private BatchWriter<EngineerTracePO> batchWriter;
    
    @Inject
    public EngineerEventService(AMQClient mqclient, IEventRepository repository) {
        // subscribe ENGINEER_EVENT topic
        mqclient.subscribe(EventTopic.ENGINEER_EVENT.name(), this);
        logger.debug("subscribe topic {}",EventTopic.ENGINEER_EVENT.name());
        batchWriter = new EngineerEventBatchWriter(repository);
        batchWriter.start();
    }
    
    @Override
    public void onMessage(String topic, Object content) {
        try {
            if (String.class.isInstance(content)) {
                EventContent<?> event = JSONHelper.fromJSON((String)content, EventContent.class);
                
                switch(event.getCode()) {
                    case ENGINEER_TRACE: {
                        logger.debug("recv engineer position {}",content);
                        EngineerTracePO engineerTracePO = JSONHelper.convertToObject(event.getContent(), EngineerTracePO.class);
                        batchWriter.push(engineerTracePO);
                        return;
                    }
                    default: {
                        logger.info("ignore {}", event.getCode());
                    }
                }
            }
        }
        catch (Exception exp) {
            TraceableException.writeLog(ErrorCode.MQ_ERROR, "", exp);
        }
    }
}
